package org.oak.filter;

/**
 * org.oak.filter.CharacterEncodingFilter
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/10/30 17:57
 */
import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String initEncoding = filterConfig.getInitParameter("encoding");
        if (initEncoding != null) {
            this.encoding = initEncoding;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 设置请求编码
        request.setCharacterEncoding(encoding);
        // 设置响应编码
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset=" + encoding);

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 无需特殊处理
    }
}